﻿using Inaction.Rule;
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace Inaction.Database
{
    public partial class DbConfigForm : Form
    {
        #region 属性
        private List<DbProviderInfo> WorkingProviders
        {
            get { return providerTypeInfoBindingSource.DataSource as List<DbProviderInfo>; }
        }

        private DbProviderInfo WorkingProvider
        {
            get { return providerTypeInfoBindingSource.Current as DbProviderInfo; }
            set { providerTypeInfoBindingSource.Position = providerTypeInfoBindingSource.IndexOf(value); }
        }

        #endregion

        #region 构造
        public DbConfigForm()
        {
            InitializeComponent();
            providerTypeInfoBindingSource.DataSource = DbProviderManager.Providers;
            sqlTypeBindingSource.DataSource = Rule.EnumDescriptionList.Query(typeof(SqlType));
        }
        #endregion

        #region 事件
        #region 数据库驱动

        private void btn_OpenProviderFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFile = new OpenFileDialog();
            openFile.Filter = "动态链接库|*.dll";
            openFile.InitialDirectory = Inaction.Util.AppHelper.ExecuteDirectory;
            openFile.ShowDialog();
            if (!string.IsNullOrEmpty(openFile.FileName))
            {
                var providerType = Inaction.Util.TypeHelper.GetSubClassType<System.Data.Common.DbProviderFactory
>(openFile.FileName);
                if (providerType.Count != 0)
                {
                    var startIndex = openFile.FileName.LastIndexOf("\\");
                    var fileName = openFile.FileName.Substring(startIndex + 1);
                    if (!System.IO.File.Exists(Inaction.Util.AppHelper.ExecuteDirectory + fileName))
                    {
                        System.IO.File.Copy(openFile.FileName, Inaction.Util.AppHelper.ExecuteDirectory + fileName, true);
                    }
                    tb_Provider.Text = string.Empty;
                    tb_File.Text = fileName;
                    btn_OpenProviderFile.Tag = tb_Provider.Text;
                    tb_Factory.Text = providerType[0].FullName;
                }
            }
        }
        #endregion

        private void btn_Save_Click(object sender, EventArgs e)
        {
            DbProviderManager.Save();
            Close();
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion
    }
}
